#encoding=utf8
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import  train_test_split


#encoding=utf8
import numpy as np
class SVM:
    def __init__(self, max_iter=100, kernel='linear'):
        '''
        input:max_iter(int):最大训练轮数
              kernel(str):核函数，等于'linear'表示线性，等于'poly'表示多项式
        '''
        self.max_iter = max_iter
        self._kernel = kernel
    #初始化模型
    def init_args(self, features, labels):
        self.m, self.n = features.shape
        self.X = features
        self.Y = labels
        self.b = 0.0
        # 将Ei保存在一个列表里
        self.alpha = np.ones(self.m)
        self.E = [self._E(i) for i in range(self.m)]
        # 松弛变量
        self.C = 1.0
    #********* Begin *********#  

    #kkt条件    
    
    # g(x)预测值，输入xi（X[i]）
    def _G(self, id:int):
        return self.predict(self.X[id])


    # 核函数
    def kernel(self, xi:np.ndarray, xj:np.ndarray):
        if self._kernel == "linear":
            return xi.T.dot(xj)
        else:
            pass

    # E（x）为g(x)对输入x的预测值和y的差
    def _E(self, id:int):
        return self._G(id) - self.Y[id]

    #初始alpha

    #选择参数   

    #训练
    def fit(self, features, labels):
        self.init_args(features, labels)
        print(self._weight())

    #********* End *********#        
    def predict(self, data):
        r = self.b
        for i in range(self.m):
            r += self.alpha[i] * self.Y[i] * self.kernel(data, self.X[i])
        return 1 if r > 0 else -1
    
    def score(self, X_test, y_test):
        right_count = 0
        for i in range(len(X_test)):
            result = self.predict(X_test[i])
            if result == y_test[i]:
                right_count += 1
        return right_count / len(X_test)
        
    def _weight(self):
        yx = self.Y.reshape(-1, 1)*self.X
        self.w = np.dot(yx.T, self.alpha)
        return self.w



#获取并处理鸢尾花数据
def create_data():
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['label'] = iris.target
    df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
    data = np.array(df.iloc[:100, [0, 1, -1]])
    #将标签为0的数据标签改为-1
    for i in range(len(data)):
        if data[i,-1] == 0:
            data[i,-1] = -1
    return data[:,:2], data[:,-1]

x,y = create_data()
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2,random_state=22)
svm = SVM()
svm.fit(x_train,y_train) 

acc = svm.score(x_test,y_test) 
if acc > 0.95 :
    print('正确率大于0.95')
else:
    print('正确率为:%.3f,请修改'%acc)